package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.common.UserHolder;
import com.itheima.pojo.*;
import com.itheima.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    //生成订单
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        //1.获取用户id，获取用户信息
        Long userid = UserHolder.getCurrentId();
        User user = userService.getById(userid);
        //2.获取购物车信息
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userid);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(qw);
        //判断购物车是否为空
        if (shoppingCartList == null) {
            throw new CustomException("购物车为空，不支持下单。");
        }
        //3.获取地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }
        //获取订单id(工具类随机生成)
        long ordersId = IdWorker.getId();
        //总价
        BigDecimal amount = new BigDecimal(0);
        List<OrderDetail> orderDetails = shoppingCartList.stream().map((shoppingCart) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());//图片
            orderDetail.setOrderId(ordersId);//订单id
            orderDetail.setDishId(shoppingCart.getDishId());//菜品id
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());//口味id
            orderDetail.setSetmealId(shoppingCart.getSetmealId());//套餐id
            orderDetail.setNumber(shoppingCart.getNumber());//数量
            amount.add(shoppingCart.getAmount().multiply(BigDecimal.valueOf(shoppingCart.getNumber())));//总金额
            orderDetail.setAmount(amount);//获取总金额
            return orderDetail;
        }).collect(Collectors.toList());
        //3.向订单表插入数据
        orders.setId(ordersId);//订单id
        orders.setNumber(String.valueOf(ordersId));//订单号
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userid);//用户id
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setPhone(user.getPhone());//联系号码
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setAddress((addressBook.getProvinceCode() == null ? "" : addressBook.getProvinceCode())
                + (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityCode() == null ? "" : addressBook.getCityCode())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityCode()));//省+市+区域+详细地址
        orders.setAmount(amount);//总金额
        //保存订单
        orderService.save(orders);
        //保存订单明细表数据
        orderDetailService.saveBatch(orderDetails);
        //下单完成，清空购物车
        shoppingCartService.remove(qw);
        return R.success("下单完成");
    }

    //分页查询订单
    @GetMapping("/{userPage}")
    public R<Map> select(@RequestParam Integer page, Integer pageSize) {
        //条件构造器
        Page<Orders> pg = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Orders::getCheckoutTime);
        orderService.page(pg, qw);
        Map<String, Object> map = new HashMap();
        long total = pg.getTotal();
        List<Orders> records = pg.getRecords();
        map.put("total", total);
        map.put("records", records);
        return R.success(map);
    }
}
